<template>
    <view class="reservise-page">
        <view class="section">
            <text class="section-title">选择套餐</text>
            <picker :range="packages" range-key="name" @change="onPackageChange">
                <view class="picker-value">{{ selectedPackage ? selectedPackage.name : '请选择套餐' }}</view>
            </picker>
        </view>

        <view class="section">
            <text class="section-title">选择技师</text>
            <picker :range="filteredTechnicians" range-key="username" @change="onTechnicianChange">
                <view class="picker-value">{{ selectedTechnician ? selectedTechnician.username : '请选择技师' }}</view>
            </picker>
        </view>

        <view class="section">
            <text class="section-title">选择日期和时间</text>
            <view class="date-range">
                <picker mode="date" @change="onDateChange">
                    <view class="picker-value">{{ date ? date : '请选择日期' }}</view>
                </picker>
            </view>
            <view class="time-range">
                <view class="time-picker">
                    <text class="picker-label">开始时间：</text>
                    <picker mode="time" start="09:00" end="21:00" @change="onStartTimeChange">
                        <view class="picker-value">{{ startTime ? startTime : '请选择开始时间' }}</view>
                    </picker>
                </view>
                <text class="divider">-</text>
                <view class="time-picker">
                    <text class="picker-label">结束时间：</text>
                    <picker mode="time" start="09:00" end="22:00" @change="onEndTimeChange">
                        <view class="picker-value">{{ endTime ? endTime : '请选择结束时间' }}</view>
                    </picker>
                </view>
            </view>
        </view>

        <view class="section">
            <text class="section-title">备注</text>
            <textarea v-model="remark" placeholder="请输入备注内容" class="remark-area" />
        </view>

        <view class="section">
            <button class="submit-btn" @click="submitReservation">提交预约</button>
        </view>

        <reserve-tabber :current="2" />
    </view>
</template>

<script>
import ReserveTabber from '@/components/reserve-tabber.vue';
function uuid() {
    return 'xxxxxxxyxxxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}
export default {
    components: { ReserveTabber },
    data() {
        return {
            packages: [], // 后端获取套餐
            technicians: [], // 后端获取技师
            selectedPackage: null,
            selectedTechnician: null,
            date: '',
            startTime: '',
            endTime: '',
            productDetail: {},
            productTitle: '',
            currentPrice: '',
            originPrice: '',
            productDesc: '',
            productSoldCount: '',
            productHotTag: '',
            productBannerImg: '',
            remark: '',
            isOnline: true,
            netType: '',
            localReservations: [],
            syncing: false,
            syncResult: ''
        };
    },
    onLoad(options) {
        // 网络状态初始化
        uni.getNetworkType({
            success: (res) => {
                this.netType = res.networkType;
                this.isOnline = res.networkType !== 'none';
            }
        });
        uni.onNetworkStatusChange((res) => {
            this.isOnline = res.isConnected;
            this.netType = res.networkType;
            if (res.isConnected) {
                this.syncLocalReservations();
            }
        });
        // 读取本地未同步数据
        this.loadLocalReservations();
        // 获取套餐详情
        const id = options.id;
        uni.request({
            url: `https://vue.maylab.top/api/quick-registration/services/${id}`,
            method: 'GET',
            success: (res) => {
                if (res.statusCode === 200 && res.data && res.data.data) {
                    const detail = res.data.data;
                    this.productDetail = detail;
                    this.productTitle = detail.name;
                    this.currentPrice = detail.price;
                    this.originPrice = detail.origin || detail.price;
                    this.productDesc = detail.description;
                    this.productSoldCount = detail.sale || '';
                    this.productHotTag = detail.hotTag || '';
                    this.productBannerImg = detail.image || '/static/1.jpg';
                    // 只显示当前套餐
                    this.packages = [detail];
                    this.selectedPackage = detail;
                } else {
                    uni.showToast({ title: '套餐详情数据异常', icon: 'none' });
                }
            },
            fail: (err) => {
                uni.showToast({ title: '套餐详情加载失败', icon: 'none' });
            }
        });
        // 获取技师列表
        uni.request({
            url: `https://vue.maylab.top/api/schedules/technicians?search=&status=all`,
            method: 'GET',
            success: (res) => {
                if (res.statusCode === 200 && Array.isArray(res.data.data)) {
                    this.technicians = res.data.data;
                } else {
                    uni.showToast({ title: '技师数据异常', icon: 'none' });
                }
            },
            fail: () => {
                uni.showToast({ title: '技师列表加载失败', icon: 'none' });
            }
        });
    },
    computed: {
        filteredTechnicians() {
            if (!this.selectedPackage) return [];
            // 技师列表根据套餐id筛选
            return this.technicians.filter(t => t.packageId === this.selectedPackage.id);
        }
    },
    methods: {
        onPackageChange(e) {
            this.selectedPackage = this.packages[e.detail.value];
            this.selectedTechnician = null;
        },
        onTechnicianChange(e) {
            this.selectedTechnician = this.filteredTechnicians[e.detail.value];
        },
        onDateChange(e) {
            this.date = e.detail.value;
        },
        onStartTimeChange(e) {
            this.startTime = e.detail.value;
        },
        onEndTimeChange(e) {
            this.endTime = e.detail.value;
        },
        // 本地预约数据加载
        loadLocalReservations() {
            const arr = uni.getStorageSync('localReservations') || [];
            this.localReservations = arr;
        },
        // 本地预约数据保存
        saveLocalReservation(data) {
            const arr = uni.getStorageSync('localReservations') || [];
            arr.push(data);
            uni.setStorageSync('localReservations', arr);
            this.localReservations = arr;
        },
        // 本地预约数据状态更新
        updateLocalReservationStatus(id, status) {
            const arr = uni.getStorageSync('localReservations') || [];
            arr.forEach(item => { if (item.id === id) item.syncStatus = status; });
            uni.setStorageSync('localReservations', arr);
            this.localReservations = arr;
        },
        // 手动同步按钮
        manualSync() {
            this.syncLocalReservations();
        },
        // 自动/手动同步本地预约
        async syncLocalReservations() {
            if (this.syncing) return;
            const arr = uni.getStorageSync('localReservations') || [];
            const unsynced = arr.filter(item => item.syncStatus === '未同步' || !item.syncStatus);
            if (unsynced.length === 0) return;
            this.syncing = true;
            let successCount = 0, failCount = 0;
            for (let item of unsynced) {
                try {
                    await new Promise((resolve, reject) => {
                        uni.request({
                            url: `https://vue.maylab.top/uni/events?technician=${item.technician}`,
                            method: 'POST',
                            data: item.data,
                            success: (res) => {
                                if (res.statusCode === 200) {
                                    this.updateLocalReservationStatus(item.id, '已同步');
                                    successCount++;
                                    resolve();
                                } else {
                                    this.updateLocalReservationStatus(item.id, '同步失败');
                                    failCount++;
                                    reject();
                                }
                            },
                            fail: () => {
                                this.updateLocalReservationStatus(item.id, '同步失败');
                                failCount++;
                                reject();
                            }
                        });
                    });
                } catch (e) {}
            }
            this.syncing = false;
            this.syncResult = `${successCount}条数据已同步，${failCount}条失败`;
            this.loadLocalReservations();
        },
        submitReservation() {
            if (!this.selectedPackage || !this.selectedTechnician) {
                uni.showToast({ title: '请选择套餐和技师', icon: 'none' });
                return;
            }
            if (!this.date || !this.startTime || !this.endTime) {
                uni.showToast({ title: '请选择完整日期和时间', icon: 'none' });
                return;
            }
            // 拼接时间格式 yyyy-MM-dd HH:mm:ss.000
            function formatDateTime(date, time) {
                return date + ' ' + time + ':00.000';
            }
            const data = {
                technician: this.selectedPackage._id || this.selectedPackage.id,
                title: this.selectedPackage.name,
                start: formatDateTime(this.date, this.startTime),
                end: formatDateTime(this.date, this.endTime),
                notes: this.remark,
                user: this.selectedTechnician
            };
            if (!this.isOnline) {
                // 断网本地保存
                const localData = {
                    id: uuid(),
                    data,
                    technician: data.technician,
                    createTime: Date.now(),
                    syncStatus: '未同步'
                };
                this.saveLocalReservation(localData);
                uni.showToast({ title: '当前无网络，数据已保存，将在网络恢复后自动同步', icon: 'none' });
            } else {
                // 联网直接提交
                uni.request({
                    url: `https://vue.maylab.top/uni/events?technician=${data.technician}`,
                    method: 'POST',
                    data,
                    success: (res) => {
                        if (res.statusCode === 200) {
                            uni.showModal({
                                title: '预约成功',
                                content: '即将返回',
                                showCancel: false,
                                success: (modalRes) => {
                                    if (modalRes.confirm) {
                                        uni.navigateBack();
                                    }
                                }
                            });
                        } else {
                            uni.showToast({ title: '预约失败', icon: 'none' });
                        }
                    },
                    fail: () => {
                        // 联网失败也本地保存
                        const localData = {
                            id: uuid(),
                            data,
                            technician: data.technician,
                            createTime: Date.now(),
                            syncStatus: '未同步'
                        };
                        this.saveLocalReservation(localData);
                        uni.showToast({ title: '网络错误，数据已保存，将在网络恢复后自动同步', icon: 'none' });
                    }
                });
            }
        }
    }
};
</script>

<style scoped>
.reservise-page {
    padding: 16px;
    background: #f8f8f8;
    min-height: 100vh;
}

.section {
    margin-bottom: 24px;
    background: #fff;
    border-radius: 8px;
    padding: 16px;
}

.section-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 12px;
    display: block;
}

.picker-value {
    padding: 8px 0;
    color: #666;
}

.date-range {
    display: flex;
    gap: 10px;
    margin-bottom: 8px;
}

.date-btn {
    padding: 6px 12px;
    border-radius: 4px;
    border: 1px solid #ddd;
    background: #f5f5f5;
    color: #333;
}

.date-btn.active {
    background: red;
    color: #fff;
}

.custom-date {
    margin-top: 8px;
}

.divider {
    margin: 0 8px;
}

.submit-btn {
    width: 100%;
    background: red;
    color: #fff;
    padding: 12px;
    border-radius: 8px;
    font-size: 16px;
}

.remark-area {
    width: 100%;
    min-height: 80px;
    padding: 8px;
    border: 1px solid #ddd;
    border-radius: 6px;
    font-size: 15px;
    margin-top: 8px;
    box-sizing: border-box;
}

.time-range {
    display: flex;
    align-items: center;
    margin-top: 8px;
}

.time-picker {
    display: flex;
    align-items: center;
}

.picker-label {
    margin-right: 8px;
    color: #888;
    font-size: 15px;
}
</style>